﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace com.hebg3.app.security {
  public class RsaUtil {

    
    public static String[] getKeys() {
      String[] keys = new String[2];
      RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
     

      keys[0] = rsa.ToXmlString(false);     
      keys[1] = rsa.ToXmlString(true);

      return keys;
    }
    /// <summary>        /// RSA加密        /// </summary>        /// <param name="publickey"></param>        /// <param name="content"></param>        /// <returns></returns>       
    public static string RSAEncrypt(string publicKey, string content) {
      
      RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
      byte[] cipherbytes;
      rsa.FromXmlString(publicKey);
      cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false);
      return Convert.ToBase64String(cipherbytes);
    }
    /// <summary>        /// RSA解密        /// </summary>        /// <param name="privatekey"></param>        /// <param name="content"></param>    
    /// /// <returns></returns>        
    public static string RSADecrypt(string privateKey, string content) {
      if(content.Length == 0){
        return "";
      }
      RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
      byte[] cipherbytes;
      rsa.FromXmlString(privateKey);
      cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false);
      return Encoding.UTF8.GetString(cipherbytes);
    }
    /*static void Main(string[] args) {
      getKeys();
      String name = "sb";
      String XX = RSAEncrypt(null, name);
      Console.WriteLine(XX);
      Console.WriteLine("---------->");
      Console.WriteLine(RSADecrypt(null, XX));
      Console.ReadKey();
    }*/
  }
}
